//
//  ZXRegister ViewController.m
//  demo
//
//  Created by maxine on 2016/11/14.
//  Copyright © 2016年 maxine. All rights reserved.
//

#import "ZXRegisterViewController.h"
#import "ZXRegisterTwoController.h"
#import "ZXHTTPManager.h"

@interface ZXRegisterViewController ()<UIPickerViewDataSource,UIPickerViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
{
    NSTimer *_timer;
    NSInteger verificationTimeCount;
    NSString *_headIconImg;
}


/**
 图片icon 和btn
 */
@property (weak, nonatomic) IBOutlet UIImageView *iconImg;
@property (weak, nonatomic) IBOutlet UIButton *iconBtn;


@property (weak, nonatomic) IBOutlet UIImageView *icon;

/**
 手机号 验证码textField
 */
@property (weak, nonatomic) IBOutlet UITextField *phoneTf;
@property (weak, nonatomic) IBOutlet UITextField *vercodeTf;


/**
 获取验证码按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *verCodeBtn;



@property (weak, nonatomic) IBOutlet UITextField *passTf;
@property (weak, nonatomic) IBOutlet UITextField *secPassTf;





/**
 身份类型
 */
@property (weak, nonatomic) IBOutlet UITextField *roleTypeTf;

@property (strong, nonatomic) UIPickerView *rolePickerView;


@property (weak, nonatomic) IBOutlet UIButton *nextStep;




@end

@implementation ZXRegisterViewController



/**
 头像按钮点击

 @param sender 按钮
 */
- (IBAction)iconBtnClick:(id)sender {
    
    WeakSelf(WSelf);
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * cancelAction =[UIAlertAction actionWithTitle:@"取消"
                                                           style:(UIAlertActionStyleCancel)
                                                         handler:^(UIAlertAction * _Nonnull action) {
                                                             
                                                         }];
    
    UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"拍摄照片"
                                                           style:(UIAlertActionStyleDefault)
                                                         handler:^(UIAlertAction * _Nonnull action) {
                                                             [WSelf takePhoto];

                                                         }];
    
    
    UIAlertAction * action2 =[UIAlertAction actionWithTitle:@"从手机相册选择"
                                                         style:(UIAlertActionStyleDefault)
                                                       handler:^(UIAlertAction * _Nonnull action) {
                                                           
                                                           [WSelf LocalPhoto];
                                                       
                                                       }];
    [alertController addAction:cancelAction];
    [alertController addAction:action1];
    [alertController addAction:action2];

    [self presentViewController:alertController animated:true completion:nil];
    
}


//判断手机号码格式是否正确
- (BOOL)valiMobile:(NSString *)mobile
{
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11)
    {
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}



-(BOOL)checkPassWord
{
    if (self.passTf.text.length < 6) {
        HUDNormal(@"请输入不小于6位数的密码");
        return NO;

    }else if(self.passTf.text.length > 32){
        HUDNormal(@"密码长度超长");
        return NO;

    }
    //6-20位数字和字母组成
    NSString *regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,32}$";
    NSPredicate *   pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if ([pred evaluateWithObject:self.passTf.text]) {
        return YES ;
    }else
        return NO;
}


- (IBAction)next:(id)sender {
    
    if (![self valiMobile:self.phoneTf.text]) {
        HUDNormal(@"请检查您输入的手机号码!");
        return;
    };
    
    if (![self checkPassWord]) {
        HUDNormal(@"密码必须是6-32位数字或字母组合");
        return;
    }
    
    if (![self.passTf.text isEqualToString:self.secPassTf.text]) {
        HUDNormal(@"两次输入的密码不一致,请检查");
        return;
    }

    
    if (![self.vercodeTf.text isEqualToString:[[NSUserDefaults standardUserDefaults]valueForKey:@"captcha_key"]] ) {
        HUDNormal(@"验证码不正确");
        return;
    }

    
    ZXRegisterTwoController *twoVc = [[ZXRegisterTwoController alloc]init];
    twoVc.phone = self.phoneTf.text;
    twoVc.password = self.passTf.text;
    if ([self.roleTypeTf.text isEqualToString:@"小农"]) {
        twoVc.roleType = @"1";
    }
    else if([self.roleTypeTf.text isEqualToString:@"农场员工"]){
        twoVc.roleType = @"2";
    }
    else if([self.roleTypeTf.text isEqualToString:@"散户"]){
        twoVc.roleType = @"3";
    }
    else{
        HUDNormal(@"请检查身份");
    }
    twoVc.headIconImg = _headIconImg;
    
    [self.navigationController pushViewController:twoVc animated:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"注册";

    self.iconImg.layer.cornerRadius = 60/2;
    self.iconImg.layer.masksToBounds = YES;
    
    
    
    self.nextStep.userInteractionEnabled = NO;
    self.nextStep.alpha = 0.5;
    
    self.roleTypeTf.inputView = self.rolePickerView;
    [self.roleTypeTf reloadInputViews];
    
    //监听按钮
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(change:) name:UITextFieldTextDidEndEditingNotification object:nil];
    
}
-(void)change:(NSNotification *)notification
{
    //判断下一步按钮是否可以点击
    if (self.phoneTf.text.length>0&&self.vercodeTf.text.length>0&&self.passTf.text.length>0
        &&self.secPassTf.text.length>0&&self.roleTypeTf.text.length>0
        ) {
        self.nextStep.userInteractionEnabled = YES;
        self.nextStep.alpha = 1;
    }else{
        self.nextStep.alpha = 0.5;
        self.nextStep.userInteractionEnabled = NO;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}




/**
 懒加载pickerView

 @return pickerView
 */
- (UIPickerView *)rolePickerView{

    if (!_rolePickerView) {
        _rolePickerView = [[UIPickerView alloc]init];
        _rolePickerView.delegate = self;
        _rolePickerView.dataSource = self;
    }
    return _rolePickerView;
}

//数据源方法
//返回列
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

//返回行
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return 4;
}

//代理方法
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    NSString *str = @"";
    switch (row) {
        case 0:
            str = @"请选择";
            break;
        case 1:
            str = @"散户";
            break;
        case 2:
            str = @"农场员工";
            break;
        case 3:
            str = @"小农";
            break;
        default:
            break;
    }
    return str;
}

//代理方法
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    switch (row) {
        case 0:
            self.roleTypeTf.text = @"请选择";
            break;
        case 1:
            self.roleTypeTf.text = @"散户";
            break;
        case 2:
            self.roleTypeTf.text = @"农场员工";
            break;
        case 3:
            self.roleTypeTf.text = @"小农";
            break;
        default:
            break;
    }
}











/**
 获取验证码按钮点击

 */
- (IBAction)VerBtnClick:(UIButton *)sender {

    
    if (![self valiMobile:self.phoneTf.text]) {
        HUDNormal(@"请检查您输入的手机号码!");
        return;
    };
    
    //    HUDLoading(@"");
    sender.enabled = NO;
    [self cheackCodeTime:0];
    
    //    sender.backgroundColor = [UIColor grayColor];
//    NSMutableDictionary *param = [NSMutableDictionary new];
//    param[@"telephone"] = _phoneTf.text;

    //此处增加获取验证码相关逻辑
    [[ZXHTTPManager sharedManager] gevfcodeTel:_phoneTf.text completed:^(NSDictionary *jsonDict, NSError *error) {
        if (error) {
            NSLog(@"error = %@",error);
            HUDNormal(@"请检查您的网络");
            return ;
        }
        HUDNormal(jsonDict[@"message"]);
        NSLog(@"jsonDict = %@",jsonDict);

        if ([jsonDict[@"result"] count]) {
            [[NSUserDefaults standardUserDefaults] setObject:jsonDict[@"result"][0][@"captcha"] forKey:@"captcha_key"];
        }
        
    }];
    
}



- (void)cheackCodeTime:(NSInteger)type
{
    if (type) {
        [self.verCodeBtn setTitle:[NSString stringWithFormat:@"%ld秒后重发",(long)verificationTimeCount] forState:UIControlStateNormal];
        
    }else{
        verificationTimeCount = 60;
    }
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countPass) userInfo:nil repeats:YES];
}

- (void)countPass
{
    verificationTimeCount --;
    if (verificationTimeCount <= 0) {
        [_timer invalidate];
        [self.verCodeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self.verCodeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
        self.verCodeBtn.enabled = YES;
        //        self.verCodeBtn.backgroundColor = GeneralBackColor;
        verificationTimeCount = 60;
    }else{
        [self.verCodeBtn setTitle:[NSString stringWithFormat:@"%ld秒后重发",(long)verificationTimeCount] forState:UIControlStateNormal];
        self.verCodeBtn.enabled = NO;
    }
}


// ------- 选择图片相关逻辑
#pragma mark -

//开始拍照
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    }else
    {
        NSLog(@"模拟其中无法打开照相机,请在真机中使用");
    }
}

//打开本地相册
-(void)LocalPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
}

//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        NSData *data;
        
        
        
        if (UIImagePNGRepresentation(image) == nil)
        {
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        else
        {
            data = UIImagePNGRepresentation(image);
        }
        
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
        
        //得到选择后沙盒中图片的完整路径
        //        NSString *filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.png"];
        
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:nil];
        
        //创建一个选择后图片的小图标放在下方
        //类似微薄选择图后的效果
        //        UIImageView *smallimage = [[UIImageView alloc] initWithFrame:self.userImageView.frame];
        //
        //        smallimage.image = image;
        //        //加在视图中
        //        [self.view addSubview:smallimage];
        
        
        self.iconImg.image = image;
        
        //此处上传图片的 逻辑
        UIImage *uploadImage = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        NSData *Imgdata = UIImageJPEGRepresentation(uploadImage, 0.1);
        
        NSString * urlString = @"http://139.129.199.137:8080/resources/api/v1/base/attach/";
//        NSURL * url = [NSURL URLWithString:@"file:///Users/stone/Pictures/6.jpg"];
        ZXHTTPManager * manager =    [ZXHTTPManager sharedManager];
        
        NSMutableDictionary * dict = [NSMutableDictionary dictionary];
        dict[@"name"] = @"666.png"; // 必须得写扩展名 , 不然上传失败
        dict[@"file"] = Imgdata;
        //需设置请求头
        [[manager requestSerializer]setValue:@"application/json; Charset=UTF-8" forHTTPHeaderField:@"Accept"];
        [manager POST:urlString parameters:dict constructingBodyWithBlock:^(id<ZXMultipartFormData> _Nonnull formData) {
            
            // formData :就是请求体格式.
            // 参数:
            // 1. FileURL :需要上传的文件的本地路径.
            // 2. name : 服务器接收文件参数的 key 值.
            // 3. fileName :上传文件在服务器中保存的名称.
            // 4. mimeType :上传文件的类型.
            // 5. error :NULL
//            [formData appendPartWithFileURL:url name:@"name" fileName:dict[@"name"] mimeType:@"image/png" error:NULL];
            [formData appendPartWithFileData:data name:@"name" fileName:[NSString stringWithFormat:@"%.0f.png", [NSDate date].timeIntervalSinceReferenceDate] mimeType:@"image/png"];

        }
             progress:^(NSProgress * _Nonnull uploadProgress) {
                 //
                 NSLog(@"uploadProgress = %@",uploadProgress);
             }
              success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
                  //
                  NSString *response = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                  
                  HUDNormal([response mj_JSONObject][@"message"]);
                  if ([response mj_JSONObject][@"success"]) {
                      NSString *iconimgUrl = [NSString stringWithFormat:@"http://139.129.199.137:8080/resources/api/v1/base/attach/%@/down/",[response mj_JSONObject][@"result"][@"id"]];
                      _headIconImg = iconimgUrl;
                  }
                  NSLog(@"responseObject = %@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
              }
              failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){
                  //
                  
                  HUDNormal(@"图片上传失败,请重试!");
                  NSLog(@"error = %@", error);
              }];
    }
}



// get mimeType
- (NSString *)mimeType:(NSURL *)url{
    __block dispatch_semaphore_t sem = dispatch_semaphore_create(0);//信号0
    
    __block NSString * mimetype;
    
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    
    NSURLSessionDataTask * task =[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        mimetype = response.MIMEType;
        
        dispatch_semaphore_signal(sem);//信号+1
        
    }] ;
    
    [task resume];
    
    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);// 信号 0就一直等待
    
    return mimetype;
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    NSLog(@"您取消了选择图片");
    [picker dismissViewControllerAnimated:YES completion:nil];
}




@end
